<template>
  <div class="prices-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">价格管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="prices" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="价格管理"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增价格
            </el-button>
            <el-button type="success" @click="handleBatchAdjust">
              <el-icon><Refresh /></el-icon>
              批量调价
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="价格类型">
          <el-select v-model="searchForm.priceType" placeholder="请选择价格类型" clearable>
            <el-option label="采购价" value="purchase" />
            <el-option label="销售价" value="sale" />
            <el-option label="VIP价" value="vip" />
            <el-option label="批发价" value="wholesale" />
            <el-option label="零售价" value="retail" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效日期">
          <el-date-picker
            v-model="searchForm.effectiveDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchEnable">批量启用</el-button>
              <el-button size="small" type="warning" @click="handleBatchDisable">批量停用</el-button>
              <el-button size="small" type="primary" @click="handleBatchAdjustSelected">批量调价</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="materialCode" label="物料编码" width="150" />
        <el-table-column prop="materialName" label="物料名称" width="200" />
        <el-table-column prop="priceType" label="价格类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getPriceTypeTag(row.priceType)">
              {{ getPriceTypeName(row.priceType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold; font-size: 16px;">
              ¥{{ row.price.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="oldPrice" label="原价" width="120">
          <template #default="{ row }">
            {{ row.oldPrice ? '¥' + row.oldPrice.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="priceChange" label="调价幅度" width="120">
          <template #default="{ row }">
            <span v-if="row.oldPrice" :style="{ color: row.price > row.oldPrice ? '#f56c6c' : '#67c23a' }">
              {{ ((row.price - row.oldPrice) / row.oldPrice * 100).toFixed(2) }}%
              <el-icon v-if="row.price > row.oldPrice"><Top /></el-icon>
              <el-icon v-else><Bottom /></el-icon>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="币种" width="100" />
        <el-table-column prop="minQuantity" label="最小数量" width="100" />
        <el-table-column prop="effectiveDate" label="生效日期" width="120" />
        <el-table-column prop="expiryDate" label="失效日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="success" @click="handleCopy(row)">复制</el-button>
            <el-button link type="info" @click="handleViewHistory(row)">历史</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="700px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格类型" prop="priceType">
              <el-select v-model="form.priceType" placeholder="请选择价格类型">
                <el-option label="采购价" value="purchase" />
                <el-option label="销售价" value="sale" />
                <el-option label="VIP价" value="vip" />
                <el-option label="批发价" value="wholesale" />
                <el-option label="零售价" value="retail" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="form.currency">
                <el-option label="人民币(CNY)" value="CNY" />
                <el-option label="美元(USD)" value="USD" />
                <el-option label="欧元(EUR)" value="EUR" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number 
                v-model="form.price" 
                :min="0" 
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小数量" prop="minQuantity">
              <el-input-number 
                v-model="form.minQuantity" 
                :min="1" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="form.effectiveDate"
                type="date"
                placeholder="选择生效日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" prop="expiryDate">
              <el-date-picker
                v-model="form.expiryDate"
                type="date"
                placeholder="选择失效日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量调价对话框 -->
    <el-dialog 
      v-model="adjustDialogVisible" 
      title="批量调价"
      width="500px"
    >
      <el-form :model="adjustForm" label-width="120px">
        <el-form-item label="调价方式">
          <el-radio-group v-model="adjustForm.adjustType">
            <el-radio value="percentage">按百分比</el-radio>
            <el-radio value="fixed">固定金额</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="adjustForm.adjustType === 'percentage'" label="调价幅度(%)">
          <el-input-number 
            v-model="adjustForm.percentage" 
            :min="-100" 
            :max="1000"
            :precision="2"
            style="width: 100%"
          />
          <div class="tip">正数为涨价，负数为降价</div>
        </el-form-item>

        <el-form-item v-if="adjustForm.adjustType === 'fixed'" label="调整金额">
          <el-input-number 
            v-model="adjustForm.fixedAmount" 
            :precision="2"
            style="width: 100%"
          />
          <div class="tip">正数为增加，负数为减少</div>
        </el-form-item>

        <el-form-item label="生效日期">
          <el-date-picker
            v-model="adjustForm.effectiveDate"
            type="date"
            placeholder="选择生效日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="调价说明">
          <el-input 
            v-model="adjustForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入调价说明" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAdjust">确认调价</el-button>
      </template>
    </el-dialog>

    <!-- 价格历史对话框 -->
    <el-dialog 
      v-model="historyDialogVisible" 
      title="价格历史"
      width="900px"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in priceHistory"
          :key="index"
          :timestamp="item.changeTime"
          placement="top"
        >
          <el-card>
            <h4>{{ item.materialName }}</h4>
            <p>
              价格：
              <span class="old-price">¥{{ item.oldPrice.toFixed(2) }}</span>
              <el-icon><Right /></el-icon>
              <span class="new-price">¥{{ item.newPrice.toFixed(2) }}</span>
              <el-tag :type="item.newPrice > item.oldPrice ? 'danger' : 'success'" size="small">
                {{ item.newPrice > item.oldPrice ? '涨价' : '降价' }}
                {{ Math.abs((item.newPrice - item.oldPrice) / item.oldPrice * 100).toFixed(2) }}%
              </el-tag>
            </p>
            <p>操作人：{{ item.operator }}</p>
            <p v-if="item.remark">说明：{{ item.remark }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Top, Bottom, Right } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

// 搜索表单
const searchForm = reactive({
  materialName: '',
  priceType: '',
  effectiveDate: null
})

// 选中的行
const selectedRows = ref([])

// 导出列配置
const exportColumns = [
  { prop: 'materialCode', label: '物料编码' },
  { prop: 'materialName', label: '物料名称' },
  { prop: 'priceType', label: '价格类型' },
  { prop: 'price', label: '价格' },
  { prop: 'currency', label: '币种' },
  { prop: 'effectiveDate', label: '生效日期' }
]

// 表格数据
const tableData = ref([
  {
    id: 1, materialCode: 'MAT001', materialName: 'iPhone 15', priceType: 'sale',
    price: 5999, oldPrice: 5799, currency: 'CNY', minQuantity: 1,
    effectiveDate: '2024-01-01', expiryDate: '2024-12-31', status: 1
  },
  {
    id: 2, materialCode: 'MAT001', materialName: 'iPhone 15', priceType: 'vip',
    price: 5699, oldPrice: 5499, currency: 'CNY', minQuantity: 1,
    effectiveDate: '2024-01-01', expiryDate: '2024-12-31', status: 1
  },
  {
    id: 3, materialCode: 'MAT001', materialName: 'iPhone 15', priceType: 'wholesale',
    price: 5399, oldPrice: null, currency: 'CNY', minQuantity: 10,
    effectiveDate: '2024-01-01', expiryDate: '2024-12-31', status: 1
  },
  {
    id: 4, materialCode: 'MAT002', materialName: 'OLED屏幕', priceType: 'purchase',
    price: 800, oldPrice: 820, currency: 'CNY', minQuantity: 1,
    effectiveDate: '2024-01-01', expiryDate: '2024-12-31', status: 1
  }
])

// 价格历史数据
const priceHistory = ref([
  {
    materialName: 'iPhone 15',
    oldPrice: 5799,
    newPrice: 5999,
    changeTime: '2024-01-15 10:30',
    operator: '张三',
    remark: '春节促销结束，恢复原价'
  },
  {
    materialName: 'iPhone 15',
    oldPrice: 5999,
    newPrice: 5799,
    changeTime: '2024-01-01 09:00',
    operator: '李四',
    remark: '春节促销活动'
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 4
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增价格')
const adjustDialogVisible = ref(false)
const historyDialogVisible = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  materialCode: '',
  materialName: '',
  priceType: '',
  price: 0,
  currency: 'CNY',
  minQuantity: 1,
  effectiveDate: '',
  expiryDate: '',
  status: 1,
  remark: ''
})

// 调价表单
const adjustForm = reactive({
  adjustType: 'percentage',
  percentage: 0,
  fixedAmount: 0,
  effectiveDate: '',
  remark: ''
})

// 表单验证规则
const rules = {
  materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  priceType: [{ required: true, message: '请选择价格类型', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  effectiveDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }]
}

// 获取价格类型标签
const getPriceTypeTag = (type) => {
  const tagMap = {
    purchase: 'primary',
    sale: 'success',
    vip: 'warning',
    wholesale: 'info',
    retail: 'danger'
  }
  return tagMap[type] || ''
}

// 获取价格类型名称
const getPriceTypeName = (type) => {
  const nameMap = {
    purchase: '采购价',
    sale: '销售价',
    vip: 'VIP价',
    wholesale: '批发价',
    retail: '零售价'
  }
  return nameMap[type] || type
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.materialName = ''
  searchForm.priceType = ''
  searchForm.effectiveDate = null
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量操作
const handleBatchEnable = () => {
  ElMessage.success('批量启用成功')
  selectedRows.value = []
}

const handleBatchDisable = () => {
  ElMessage.success('批量停用成功')
  selectedRows.value = []
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条价格吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    selectedRows.value = []
  })
}

// 导入成功回调
const handleImportSuccess = (result) => {
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 批量调价
const handleBatchAdjust = () => {
  adjustDialogVisible.value = true
}

const handleBatchAdjustSelected = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要调价的记录')
    return
  }
  adjustDialogVisible.value = true
}

const handleConfirmAdjust = () => {
  console.log('调价:', adjustForm)
  ElMessage.success('批量调价成功')
  adjustDialogVisible.value = false
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增价格'
  Object.assign(form, {
    id: null,
    materialCode: '',
    materialName: '',
    priceType: '',
    price: 0,
    currency: 'CNY',
    minQuantity: 1,
    effectiveDate: '',
    expiryDate: '',
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑价格'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 复制
const handleCopy = (row) => {
  dialogTitle.value = '复制价格'
  Object.assign(form, {
    ...row,
    id: null
  })
  dialogVisible.value = true
}

// 提交
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除价格 "${row.materialName} - ${getPriceTypeName(row.priceType)}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 查看历史
const handleViewHistory = (row) => {
  historyDialogVisible.value = true
}
</script>

<style scoped>
.prices-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.old-price {
  text-decoration: line-through;
  color: #909399;
}

.new-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
  margin: 0 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

